package com.iussoft.receiveData.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.apache.exception.BusinessException;
import com.apache.tools.DateUtils;
import com.apache.tools.MD5Utils;
import com.apache.tools.StrUtil;
import com.apache.tools.UUIDUtil;
import com.iussoft.receiveData.manager.ReceiveManager;
import com.iussoft.tools.*;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * description: 系统拦截器父类
 *
 * @author dyh 创建时间：2018年07月02日
 */
public abstract class SuperInterceptor implements HandlerInterceptor {

    protected final String RESPONSE_MSG="responseMessage";

    @Autowired
    @Qualifier("receiveManager")
    protected ReceiveManager receiveManager;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        IOUtils.closeQuietly(response.getOutputStream());
    }

    /**
     * 转换请求报文
     */
    protected RequestMessage getRequestMessage(HttpServletRequest request,String msg, RequestMessage reqMsg) {
        if(StrUtil.isNull(msg)){
            return reqMsg;
        }
        JSONObject obj = reqMsg.getContent();
        if(StrUtil.isNotNull(obj.getString("requestPwd"))) {
            String requestMsg = AesUtil.getInstance().decryptEcbMode(msg, obj.getString("requestPwd"));//解密报文
            if(StrUtil.isNull(requestMsg)){
                throw new BusinessException(UnityErrorCode.CHECK_DATA.getDesc());
            }
            reqMsg.setSourceMsg(requestMsg.replaceAll("\n","").replaceAll("\r",""));//请求报文
        } else {
            reqMsg.setSourceMsg(msg.replaceAll("\n","").replaceAll("\r",""));//请求报文
        }
        return reqMsg;
    }

    protected boolean authorityCertification(HttpServletRequest request,RequestMessage reqMsg){
        String url = request.getRequestURI();
        Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        if(null != pathVariables) {
            String value = String.valueOf(pathVariables.get("interfaceCode"));
            JSONObject obj = null;
            reqMsg.setRequestCode(value);
            if(url.indexOf("/data/inner/") != -1){
                obj = receiveManager.getInterfaceInfoForCode(value);
                if(obj == null){
                    return false;
                }
            } else {
                obj = receiveManager.getDxSysIntRelation(value);
                if(obj == null){
                    return false;
                }
                if(obj.containsKey("appKey") && StrUtil.isNotNull(obj.getString("appKey"))) {
                    String appId = request.getHeader("appId");
                    //String appkey = request.getHeader("appKey");
                    String key = MD5Utils.MD5(appId + obj.getString("fromInterfaceCode"));
                    if (!obj.getString("appKey").equals(key)) {
                        return false;
                    }
                }
            }
            reqMsg.setContent(obj);
        }
        return true;
    }

    /**
     * 判断是否是json结构
     */
    public static boolean isJson(String value) {
        try {
            new org.json.JSONObject(value);
        } catch (org.json.JSONException e) {
            return false;
        }
        return true;
    }

    /**
     * 获取请求IP
     */
    public static String getRequestIp(HttpServletRequest request){
        String requestIp = StrUtil.doNull(request.getParameter("useIP"),request.getHeader("useip"));
        if(StrUtil.isNull(requestIp)){
            requestIp =IpUtils.getIpAddress(request);
        }
        return requestIp;
    }

    protected void buildResponseMsg(HttpServletRequest request, String errorCode, String errorMsg,
            String reqCode) {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("responseCode", reqCode);
        data.put("errorCode", errorCode);
        data.put("errorMessage", errorMsg);
        data.put("sendTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
        request.setAttribute(RESPONSE_MSG, data);
    }

    protected Map<String, Object> buildDataMap(Map<String, Object> data, HttpServletRequest request) {
        if (null == data) {
            data = new HashMap();
            String responseCode = String.valueOf(request.getAttribute("errCode"));
            String errorMessage = String.format(String.valueOf(request.getAttribute("errMessage")), "UTF-8");
            data.put("errorCode", responseCode);
            data.put("errorMessage", errorMessage);
            data.put("responseCode", String.valueOf(request.getAttribute("requestCode")));
        }
        if (StrUtil.isNull(String.valueOf(data.get("errorCode"))))
            data.put("errorCode", UnityErrorCode.SUCCESSFUL.getValue());

        if (StrUtil.isNull(String.valueOf(data.get("errorMessage"))))
            data.put("errorMessage", UnityErrorCode.SUCCESSFUL.getDesc());
        data.put("sendTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
        data.put("timestamp", String.valueOf(System.currentTimeMillis()));
        return data;
    }

    /**
     * 获取URL参数
     */
    protected Map<String,String> getRequestParamMap(HttpServletRequest request) {
        Map<String,String> map = new HashMap();
        //得到枚举类型的参数名称，参数名称若有重复的只能得到第一个
        Enumeration enums = request.getParameterNames();
        while (enums.hasMoreElements()){
            String paramName = String.valueOf(enums.nextElement());
            if("traceId".equals(paramName)){
                continue;
            }
            String paramValue = request.getParameter(paramName);
            //形成键值对应的map
            map.put(paramName, paramValue);
        }
        return map;
    }

    public static String getTraceId(HttpServletRequest request){
        String traceId = StrUtil.doNull(request.getHeader("traceid"),request.getParameter("traceId"));
        if(StrUtil.isNull(traceId)){
            traceId = StrUtil.doNull(String.valueOf(request.getAttribute("traceId")), UUIDUtil.getPrimaryKey());
        }
        return traceId;
    }
}
